acme.sh 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864
  1. #!/usr/bin/env sh
  2. VER=2.2.9
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  7. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  8. DEFAULT_USER_AGENT="$PROJECT_ENTRY client: $PROJECT"
  9. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  10. VTYPE_HTTP="http-01"
  11. VTYPE_DNS="dns-01"
  12. VTYPE_TLS="tls-sni-01"
  13. VTYPE_TLS2="tls-sni-02"
  14. MAX_RENEW=80
  15. W_TLS="tls"
  16. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  17. END_CSR="-----END CERTIFICATE REQUEST-----"
  18. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  19. END_CERT="-----END CERTIFICATE-----"
  20. RENEW_SKIP=2
  21. if [ -z "$AGREEMENT" ] ; then
  22. AGREEMENT="$DEFAULT_AGREEMENT"
  23. fi
  24. _URGLY_PRINTF=""
  25. if [ "$(printf '\x41')" != 'A' ] ; then
  26. _URGLY_PRINTF=1
  27. fi
  28. _info() {
  29. if [ -z "$2" ] ; then
  30. echo "[$(date)] $1"
  31. else
  32. echo "[$(date)] $1='$2'"
  33. fi
  34. }
  35. _err() {
  36. _info "$@" >&2
  37. return 1
  38. }
  39. _debug() {
  40. if [ -z "$DEBUG" ] ; then
  41. return
  42. fi
  43. _err "$@"
  44. return 0
  45. }
  46. _debug2() {
  47. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  48. _debug "$@"
  49. fi
  50. return
  51. }
  52. _startswith(){
  53. _str="$1"
  54. _sub="$2"
  55. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  56. }
  57. _contains(){
  58. _str="$1"
  59. _sub="$2"
  60. echo "$_str" | grep "$_sub" >/dev/null 2>&1
  61. }
  62. _hasfield() {
  63. _str="$1"
  64. _field="$2"
  65. _sep="$3"
  66. if [ -z "$_field" ] ; then
  67. _err "Usage: str field [sep]"
  68. return 1
  69. fi
  70. if [ -z "$_sep" ] ; then
  71. _sep=","
  72. fi
  73. for f in $(echo "$_str" | tr ',' ' ') ; do
  74. if [ "$f" = "$_field" ] ; then
  75. _debug "'$_str' contains '$_field'"
  76. return 0 #contains ok
  77. fi
  78. done
  79. _debug "'$_str' does not contain '$_field'"
  80. return 1 #not contains
  81. }
  82. _exists(){
  83. cmd="$1"
  84. if [ -z "$cmd" ] ; then
  85. _err "Usage: _exists cmd"
  86. return 1
  87. fi
  88. if type command >/dev/null 2>&1 ; then
  89. command -v "$cmd" >/dev/null 2>&1
  90. else
  91. type "$cmd" >/dev/null 2>&1
  92. fi
  93. ret="$?"
  94. _debug2 "$cmd exists=$ret"
  95. return $ret
  96. }
  97. #a + b
  98. _math(){
  99. expr "$@"
  100. }
  101. _h_char_2_dec() {
  102. _ch=$1
  103. case "${_ch}" in
  104. a|A)
  105. printf "10"
  106. ;;
  107. b|B)
  108. printf "11"
  109. ;;
  110. c|C)
  111. printf "12"
  112. ;;
  113. d|D)
  114. printf "13"
  115. ;;
  116. e|E)
  117. printf "14"
  118. ;;
  119. f|F)
  120. printf "15"
  121. ;;
  122. *)
  123. printf "%s" "$_ch"
  124. ;;
  125. esac
  126. }
  127. _h2b() {
  128. hex=$(cat)
  129. i=1
  130. j=2
  131. if _exists let ; then
  132. uselet="1"
  133. fi
  134. _debug uselet "$uselet"
  135. _debug _URGLY_PRINTF "$_URGLY_PRINTF"
  136. while true ; do
  137. if [ -z "$_URGLY_PRINTF" ] ; then
  138. h="$(printf $hex | cut -c $i-$j)"
  139. if [ -z "$h" ] ; then
  140. break;
  141. fi
  142. printf "\x$h"
  143. else
  144. ic="$(printf $hex | cut -c $i)"
  145. jc="$(printf $hex | cut -c $j)"
  146. if [ -z "$ic$jc" ] ; then
  147. break;
  148. fi
  149. ic="$(_h_char_2_dec "$ic")"
  150. jc="$(_h_char_2_dec "$jc")"
  151. printf '\'"$(printf %o "$(_math $ic \* 16 + $jc)")"
  152. fi
  153. if [ "$uselet" ] ; then
  154. let "i+=2" >/dev/null
  155. let "j+=2" >/dev/null
  156. else
  157. i="$(_math $i + 2)"
  158. j="$(_math $j + 2)"
  159. fi
  160. done
  161. }
  162. #options file
  163. _sed_i() {
  164. options="$1"
  165. filename="$2"
  166. if [ -z "$filename" ] ; then
  167. _err "Usage:_sed_i options filename"
  168. return 1
  169. fi
  170. _debug2 options "$options"
  171. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  172. _debug "Using sed -i"
  173. sed -i "$options" "$filename"
  174. else
  175. _debug "No -i support in sed"
  176. text="$(cat "$filename")"
  177. echo "$text" | sed "$options" > "$filename"
  178. fi
  179. }
  180. #Usage: file startline endline
  181. _getfile() {
  182. filename="$1"
  183. startline="$2"
  184. endline="$3"
  185. if [ -z "$endline" ] ; then
  186. _err "Usage: file startline endline"
  187. return 1
  188. fi
  189. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  190. if [ -z "$i" ] ; then
  191. _err "Can not find start line: $startline"
  192. return 1
  193. fi
  194. i="$(_math "$i" + 1)"
  195. _debug i "$i"
  196. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  197. if [ -z "$j" ] ; then
  198. _err "Can not find end line: $endline"
  199. return 1
  200. fi
  201. j="$(_math "$j" - 1)"
  202. _debug j "$j"
  203. sed -n "$i,${j}p" "$filename"
  204. }
  205. #Usage: multiline
  206. _base64() {
  207. if [ "$1" ] ; then
  208. openssl base64 -e
  209. else
  210. openssl base64 -e | tr -d '\r\n'
  211. fi
  212. }
  213. #Usage: multiline
  214. _dbase64() {
  215. if [ "$1" ] ; then
  216. openssl base64 -d -A
  217. else
  218. openssl base64 -d
  219. fi
  220. }
  221. #Usage: hashalg [outputhex]
  222. #Output Base64-encoded digest
  223. _digest() {
  224. alg="$1"
  225. if [ -z "$alg" ] ; then
  226. _err "Usage: _digest hashalg"
  227. return 1
  228. fi
  229. outputhex="$2"
  230. if [ "$alg" = "sha256" ] ; then
  231. if [ "$outputhex" ] ; then
  232. echo $(openssl dgst -sha256 -hex | cut -d = -f 2)
  233. else
  234. openssl dgst -sha256 -binary | _base64
  235. fi
  236. else
  237. _err "$alg is not supported yet"
  238. return 1
  239. fi
  240. }
  241. #Usage: keyfile hashalg
  242. #Output: Base64-encoded signature value
  243. _sign() {
  244. keyfile="$1"
  245. alg="$2"
  246. if [ -z "$alg" ] ; then
  247. _err "Usage: _sign keyfile hashalg"
  248. return 1
  249. fi
  250. if [ "$alg" = "sha256" ] ; then
  251. openssl dgst -sha256 -sign "$keyfile" | _base64
  252. else
  253. _err "$alg is not supported yet"
  254. return 1
  255. fi
  256. }
  257. # _createkey 2048|ec-256 file
  258. _createkey() {
  259. length="$1"
  260. f="$2"
  261. isec=""
  262. if _startswith "$length" "ec-" ; then
  263. isec="1"
  264. length=$(printf $length | cut -d '-' -f 2-100)
  265. eccname="$length"
  266. fi
  267. if [ -z "$length" ] ; then
  268. if [ "$isec" ] ; then
  269. length=256
  270. else
  271. length=2048
  272. fi
  273. fi
  274. _info "Use length $length"
  275. if [ "$isec" ] ; then
  276. if [ "$length" = "256" ] ; then
  277. eccname="prime256v1"
  278. fi
  279. if [ "$length" = "384" ] ; then
  280. eccname="secp384r1"
  281. fi
  282. if [ "$length" = "521" ] ; then
  283. eccname="secp521r1"
  284. fi
  285. _info "Using ec name: $eccname"
  286. fi
  287. #generate account key
  288. if [ "$isec" ] ; then
  289. openssl ecparam -name $eccname -genkey 2>/dev/null > "$f"
  290. else
  291. openssl genrsa $length 2>/dev/null > "$f"
  292. fi
  293. }
  294. #_createcsr cn san_list keyfile csrfile conf
  295. _createcsr() {
  296. _debug _createcsr
  297. domain="$1"
  298. domainlist="$2"
  299. key="$3"
  300. csr="$4"
  301. csrconf="$5"
  302. _debug2 domain "$domain"
  303. _debug2 domainlist "$domainlist"
  304. if [ -z "$domainlist" ] || [ "$domainlist" = "no" ]; then
  305. #single domain
  306. _info "Single domain" "$domain"
  307. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$csrconf"
  308. openssl req -new -sha256 -key "$key" -subj "/CN=$domain" -config "$csrconf" -out "$csr"
  309. else
  310. if _contains "$domainlist" "," ; then
  311. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  312. else
  313. alt="DNS:$domainlist"
  314. fi
  315. #multi
  316. _info "Multi domain" "$alt"
  317. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName=$alt" > "$csrconf"
  318. openssl req -new -sha256 -key "$key" -subj "/CN=$domain" -config "$csrconf" -out "$csr"
  319. fi
  320. }
  321. #_signcsr key csr conf cert
  322. _signcsr() {
  323. key="$1"
  324. csr="$2"
  325. conf="$3"
  326. cert="$4"
  327. _debug "_signcsr"
  328. _msg="$(openssl x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  329. _ret="$?"
  330. _debug "$_msg"
  331. return $_ret
  332. }
  333. _ss() {
  334. _port="$1"
  335. if _exists "ss" ; then
  336. _debug "Using: ss"
  337. ss -ntpl | grep ":$_port "
  338. return 0
  339. fi
  340. if _exists "netstat" ; then
  341. _debug "Using: netstat"
  342. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  343. #for windows version netstat tool
  344. netstat -anb -p tcp | grep "LISTENING" | grep ":$_port "
  345. else
  346. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  347. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  348. else
  349. netstat -ntpl | grep ":$_port "
  350. fi
  351. fi
  352. return 0
  353. fi
  354. return 1
  355. }
  356. toPkcs() {
  357. domain="$1"
  358. pfxPassword="$2"
  359. if [ -z "$domain" ] ; then
  360. echo "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  361. return 1
  362. fi
  363. _initpath "$domain"
  364. if [ "$pfxPassword" ] ; then
  365. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  366. else
  367. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  368. fi
  369. if [ "$?" = "0" ] ; then
  370. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  371. fi
  372. }
  373. #domain [2048]
  374. createAccountKey() {
  375. _info "Creating account key"
  376. if [ -z "$1" ] ; then
  377. echo Usage: $PROJECT_ENTRY --createAccountKey -d domain.com [--accountkeylength 2048]
  378. return
  379. fi
  380. account=$1
  381. length=$2
  382. _debug account "$account"
  383. _debug length "$length"
  384. if _startswith "$length" "ec-" ; then
  385. length=2048
  386. fi
  387. if [ -z "$2" ] || [ "$2" = "no" ] ; then
  388. _info "Use default length 2048"
  389. length=2048
  390. fi
  391. _initpath
  392. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  393. _info "Account key exists, skip"
  394. return
  395. else
  396. #generate account key
  397. _createkey $length "$ACCOUNT_KEY_PATH"
  398. fi
  399. }
  400. #domain length
  401. createDomainKey() {
  402. _info "Creating domain key"
  403. if [ -z "$1" ] ; then
  404. echo Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]
  405. return
  406. fi
  407. domain=$1
  408. _initpath $domain
  409. length=$2
  410. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  411. _createkey "$length" "$CERT_KEY_PATH"
  412. else
  413. if [ "$IS_RENEW" ] ; then
  414. _info "Domain key exists, skip"
  415. return 0
  416. else
  417. _err "Domain key exists, do you want to overwrite the key?"
  418. _err "Add '--force', and try again."
  419. return 1
  420. fi
  421. fi
  422. }
  423. # domain domainlist
  424. createCSR() {
  425. _info "Creating csr"
  426. if [ -z "$1" ] ; then
  427. echo "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  428. return
  429. fi
  430. domain=$1
  431. _initpath "$domain"
  432. domainlist=$2
  433. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  434. _info "CSR exists, skip"
  435. return
  436. fi
  437. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  438. }
  439. _urlencode() {
  440. __n=$(cat)
  441. echo $__n | tr '/+' '_-' | tr -d '= '
  442. }
  443. _time2str() {
  444. #BSD
  445. if date -u -d@$1 2>/dev/null ; then
  446. return
  447. fi
  448. #Linux
  449. if date -u -r $1 2>/dev/null ; then
  450. return
  451. fi
  452. }
  453. _normalizeJson() {
  454. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  455. }
  456. _stat() {
  457. #Linux
  458. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  459. return
  460. fi
  461. #BSD
  462. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  463. return
  464. fi
  465. }
  466. #keyfile
  467. _calcjwk() {
  468. keyfile="$1"
  469. if [ -z "$keyfile" ] ; then
  470. _err "Usage: _calcjwk keyfile"
  471. return 1
  472. fi
  473. EC_SIGN=""
  474. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  475. _debug "RSA key"
  476. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  477. if [ "${#pub_exp}" = "5" ] ; then
  478. pub_exp=0$pub_exp
  479. fi
  480. _debug2 pub_exp "$pub_exp"
  481. e=$(echo $pub_exp | _h2b | _base64)
  482. _debug2 e "$e"
  483. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  484. _debug2 modulus "$modulus"
  485. n="$(printf "%s" "$modulus"| _h2b | _base64 | _urlencode )"
  486. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  487. _debug2 jwk "$jwk"
  488. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  489. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  490. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  491. _debug "EC key"
  492. EC_SIGN="1"
  493. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  494. _debug2 crv "$crv"
  495. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  496. pubi=$(_math $pubi + 1)
  497. _debug2 pubi "$pubi"
  498. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  499. pubj=$(_math $pubj + 1)
  500. _debug2 pubj "$pubj"
  501. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  502. _debug2 pubtext "$pubtext"
  503. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  504. xlen=$(_math $xlen / 4)
  505. _debug2 xlen "$xlen"
  506. xend=$(_math "$xend" + 1)
  507. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  508. _debug2 x "$x"
  509. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  510. _debug2 x64 "$x64"
  511. xend=$(_math "$xend" + 1)
  512. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  513. _debug2 y "$y"
  514. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  515. _debug2 y64 "$y64"
  516. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  517. _debug2 jwk "$jwk"
  518. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  519. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  520. else
  521. _err "Only RSA or EC key is supported."
  522. return 1
  523. fi
  524. _debug2 HEADER "$HEADER"
  525. }
  526. # body url [needbase64] [POST|PUT]
  527. _post() {
  528. body="$1"
  529. url="$2"
  530. needbase64="$3"
  531. httpmethod="$4"
  532. if [ -z "$httpmethod" ] ; then
  533. httpmethod="POST"
  534. fi
  535. _debug $httpmethod
  536. _debug "url" "$url"
  537. if _exists "curl" ; then
  538. _CURL="$CURL --dump-header $HTTP_HEADER "
  539. _debug "_CURL" "$_CURL"
  540. if [ "$needbase64" ] ; then
  541. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" --data "$body" "$url" | _base64)"
  542. else
  543. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" --data "$body" "$url" )"
  544. fi
  545. _ret="$?"
  546. if [ "$_ret" != "0" ] ; then
  547. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  548. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  549. _err "Here is the curl dump log:"
  550. _err "$(cat "$_CURL_DUMP")"
  551. fi
  552. fi
  553. else
  554. _debug "WGET" "$WGET"
  555. if [ "$needbase64" ] ; then
  556. if [ "$httpmethod"="POST" ] ; then
  557. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  558. else
  559. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  560. fi
  561. else
  562. if [ "$httpmethod"="POST" ] ; then
  563. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
  564. else
  565. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
  566. fi
  567. fi
  568. _ret="$?"
  569. if [ "$_ret" != "0" ] ; then
  570. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  571. fi
  572. _sed_i "s/^ *//g" "$HTTP_HEADER"
  573. fi
  574. _debug "_ret" "$_ret"
  575. printf "%s" "$response"
  576. return $_ret
  577. }
  578. # url getheader
  579. _get() {
  580. _debug GET
  581. url="$1"
  582. onlyheader="$2"
  583. _debug url $url
  584. if _exists "curl" ; then
  585. _debug "CURL" "$CURL"
  586. if [ "$onlyheader" ] ; then
  587. $CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" $url
  588. else
  589. $CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" $url
  590. fi
  591. ret=$?
  592. else
  593. _debug "WGET" "$WGET"
  594. if [ "$onlyheader" ] ; then
  595. $WGET --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  596. else
  597. $WGET --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - $url
  598. fi
  599. ret=$?
  600. fi
  601. _debug "ret" "$ret"
  602. return $ret
  603. }
  604. # url payload needbase64 keyfile
  605. _send_signed_request() {
  606. url=$1
  607. payload=$2
  608. needbase64=$3
  609. keyfile=$4
  610. if [ -z "$keyfile" ] ; then
  611. keyfile="$ACCOUNT_KEY_PATH"
  612. fi
  613. _debug url $url
  614. _debug payload "$payload"
  615. if ! _calcjwk "$keyfile" ; then
  616. return 1
  617. fi
  618. payload64=$(echo -n $payload | _base64 | _urlencode)
  619. _debug2 payload64 $payload64
  620. nonceurl="$API/directory"
  621. _headers="$(_get $nonceurl "onlyheader")"
  622. if [ "$?" != "0" ] ; then
  623. _err "Can not connect to $nonceurl to get nonce."
  624. return 1
  625. fi
  626. _debug2 _headers "$_headers"
  627. nonce="$( echo "$_headers" | grep "Replay-Nonce:" | head -1 | tr -d "\r\n " | cut -d ':' -f 2)"
  628. _debug nonce "$nonce"
  629. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  630. _debug2 protected "$protected"
  631. protected64="$(printf "$protected" | _base64 | _urlencode)"
  632. _debug2 protected64 "$protected64"
  633. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  634. _debug2 sig "$sig"
  635. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  636. _debug2 body "$body"
  637. response="$(_post "$body" $url "$needbase64")"
  638. if [ "$?" != "0" ] ; then
  639. _err "Can not post to $url."
  640. return 1
  641. fi
  642. _debug2 original "$response"
  643. response="$( echo "$response" | _normalizeJson )"
  644. responseHeaders="$(cat $HTTP_HEADER)"
  645. _debug2 responseHeaders "$responseHeaders"
  646. _debug2 response "$response"
  647. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  648. _debug code $code
  649. }
  650. #setopt "file" "opt" "=" "value" [";"]
  651. _setopt() {
  652. __conf="$1"
  653. __opt="$2"
  654. __sep="$3"
  655. __val="$4"
  656. __end="$5"
  657. if [ -z "$__opt" ] ; then
  658. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  659. return
  660. fi
  661. if [ ! -f "$__conf" ] ; then
  662. touch "$__conf"
  663. fi
  664. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  665. _debug2 OK
  666. if _contains "$__val" "&" ; then
  667. __val="$(echo $__val | sed 's/&/\\&/g')"
  668. fi
  669. text="$(cat $__conf)"
  670. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  671. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  672. if _contains "$__val" "&" ; then
  673. __val="$(echo $__val | sed 's/&/\\&/g')"
  674. fi
  675. text="$(cat $__conf)"
  676. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  677. else
  678. _debug2 APP
  679. echo "$__opt$__sep$__val$__end" >> "$__conf"
  680. fi
  681. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  682. }
  683. #_savedomainconf key value
  684. #save to domain.conf
  685. _savedomainconf() {
  686. key="$1"
  687. value="$2"
  688. if [ "$DOMAIN_CONF" ] ; then
  689. _setopt "$DOMAIN_CONF" "$key" "=" "\"$value\""
  690. else
  691. _err "DOMAIN_CONF is empty, can not save $key=$value"
  692. fi
  693. }
  694. #_cleardomainconf key
  695. _cleardomainconf() {
  696. key="$1"
  697. if [ "$DOMAIN_CONF" ] ; then
  698. _sed_i "s/^$key.*$//" "$DOMAIN_CONF"
  699. else
  700. _err "DOMAIN_CONF is empty, can not save $key=$value"
  701. fi
  702. }
  703. #_saveaccountconf key value
  704. _saveaccountconf() {
  705. key="$1"
  706. value="$2"
  707. if [ "$ACCOUNT_CONF_PATH" ] ; then
  708. _setopt "$ACCOUNT_CONF_PATH" "$key" "=" "\"$value\""
  709. else
  710. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  711. fi
  712. }
  713. _startserver() {
  714. content="$1"
  715. _debug "startserver: $$"
  716. nchelp="$(nc -h 2>&1)"
  717. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  718. _NC="nc -q 1 -l"
  719. else
  720. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  721. _NC="nc -c -l"
  722. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  723. _NC="nc -N -l"
  724. else
  725. _NC="nc -l"
  726. fi
  727. fi
  728. _debug "_NC" "$_NC"
  729. _debug Le_HTTPPort "$Le_HTTPPort"
  730. # while true ; do
  731. if [ "$DEBUG" ] ; then
  732. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort ; then
  733. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort ;
  734. fi
  735. else
  736. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  737. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  738. fi
  739. fi
  740. if [ "$?" != "0" ] ; then
  741. _err "nc listen error."
  742. exit 1
  743. fi
  744. # done
  745. }
  746. _stopserver(){
  747. pid="$1"
  748. _debug "pid" "$pid"
  749. if [ -z "$pid" ] ; then
  750. return
  751. fi
  752. _get "http://localhost:$Le_HTTPPort" >/dev/null 2>&1
  753. _get "https://localhost:$Le_TLSPort" >/dev/null 2>&1
  754. }
  755. # _starttlsserver san_a san_b port content
  756. _starttlsserver() {
  757. _info "Starting tls server."
  758. san_a="$1"
  759. san_b="$2"
  760. port="$3"
  761. content="$4"
  762. _debug san_a "$san_a"
  763. _debug san_b "$san_b"
  764. _debug port "$port"
  765. #create key TLS_KEY
  766. if ! _createkey "2048" "$TLS_KEY" ; then
  767. _err "Create tls validation key error."
  768. return 1
  769. fi
  770. #create csr
  771. alt="$san_a"
  772. if [ "$san_b" ] ; then
  773. alt="$alt,$san_b"
  774. fi
  775. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" ; then
  776. _err "Create tls validation csr error."
  777. return 1
  778. fi
  779. #self signed
  780. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT" ; then
  781. _err "Create tls validation cert error."
  782. return 1
  783. fi
  784. #start openssl
  785. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  786. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | openssl s_server -cert "$TLS_CERT" -key "$TLS_KEY" -accept $port -naccept 1 -tlsextdebug ) &
  787. else
  788. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | openssl s_server -cert "$TLS_CERT" -key "$TLS_KEY" -accept $port -naccept 1 >/dev/null 2>&1) &
  789. fi
  790. serverproc="$!"
  791. sleep 2
  792. _debug serverproc $serverproc
  793. }
  794. _initpath() {
  795. if [ -z "$LE_WORKING_DIR" ] ; then
  796. LE_WORKING_DIR=$HOME/.$PROJECT_NAME
  797. fi
  798. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  799. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  800. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ] ; then
  801. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  802. fi
  803. fi
  804. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  805. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  806. fi
  807. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  808. . "$ACCOUNT_CONF_PATH"
  809. fi
  810. if [ "$IN_CRON" ] ; then
  811. if [ ! "$_USER_PATH_EXPORTED" ] ; then
  812. _USER_PATH_EXPORTED=1
  813. export PATH="$USER_PATH:$PATH"
  814. fi
  815. fi
  816. if [ -z "$API" ] ; then
  817. if [ -z "$STAGE" ] ; then
  818. API="$DEFAULT_CA"
  819. else
  820. API="$STAGE_CA"
  821. _info "Using stage api:$API"
  822. fi
  823. fi
  824. if [ -z "$ACME_DIR" ] ; then
  825. ACME_DIR="/home/.acme"
  826. fi
  827. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  828. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  829. fi
  830. if [ -z "$USER_AGENT" ] ; then
  831. USER_AGENT="$DEFAULT_USER_AGENT"
  832. fi
  833. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  834. WGET="wget -q"
  835. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  836. WGET="$WGET -d "
  837. fi
  838. _CURL_DUMP="$LE_WORKING_DIR/curl.dump"
  839. CURL="curl -L --silent"
  840. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  841. CURL="$CURL --trace-ascii $_CURL_DUMP "
  842. fi
  843. if [ "$Le_Insecure" ] ; then
  844. WGET="$WGET --no-check-certificate "
  845. CURL="$CURL --insecure "
  846. fi
  847. _DEFAULT_ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  848. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  849. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  850. fi
  851. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  852. if [ -z "$CERT_HOME" ] ; then
  853. CERT_HOME="$_DEFAULT_CERT_HOME"
  854. fi
  855. domain="$1"
  856. if [ -z "$domain" ] ; then
  857. return 0
  858. fi
  859. domainhome="$CERT_HOME/$domain"
  860. mkdir -p "$domainhome"
  861. if [ -z "$DOMAIN_PATH" ] ; then
  862. DOMAIN_PATH="$domainhome"
  863. fi
  864. if [ -z "$DOMAIN_CONF" ] ; then
  865. DOMAIN_CONF="$domainhome/$domain.conf"
  866. fi
  867. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  868. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  869. fi
  870. if [ -z "$CSR_PATH" ] ; then
  871. CSR_PATH="$domainhome/$domain.csr"
  872. fi
  873. if [ -z "$CERT_KEY_PATH" ] ; then
  874. CERT_KEY_PATH="$domainhome/$domain.key"
  875. fi
  876. if [ -z "$CERT_PATH" ] ; then
  877. CERT_PATH="$domainhome/$domain.cer"
  878. fi
  879. if [ -z "$CA_CERT_PATH" ] ; then
  880. CA_CERT_PATH="$domainhome/ca.cer"
  881. fi
  882. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  883. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  884. fi
  885. if [ -z "$CERT_PFX_PATH" ] ; then
  886. CERT_PFX_PATH="$domainhome/$domain.pfx"
  887. fi
  888. if [ -z "$TLS_CONF" ] ; then
  889. TLS_CONF="$domainhome/tls.valdation.conf"
  890. fi
  891. if [ -z "$TLS_CERT" ] ; then
  892. TLS_CERT="$domainhome/tls.valdation.cert"
  893. fi
  894. if [ -z "$TLS_KEY" ] ; then
  895. TLS_KEY="$domainhome/tls.valdation.key"
  896. fi
  897. if [ -z "$TLS_CSR" ] ; then
  898. TLS_CSR="$domainhome/tls.valdation.csr"
  899. fi
  900. }
  901. _apachePath() {
  902. _APAHECTL="apachectl"
  903. if ! _exists apachectl ; then
  904. if _exists apache2ctl ; then
  905. _APAHECTL="apache2ctl"
  906. else
  907. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  908. _err "Please use webroot mode to try again."
  909. return 1
  910. fi
  911. fi
  912. httpdconfname="$($_APAHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  913. _debug httpdconfname "$httpdconfname"
  914. if _startswith "$httpdconfname" '/' ; then
  915. httpdconf="$httpdconfname"
  916. httpdconfname="$(basename $httpdconfname)"
  917. else
  918. httpdroot="$($_APAHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  919. _debug httpdroot "$httpdroot"
  920. httpdconf="$httpdroot/$httpdconfname"
  921. httpdconfname="$(basename $httpdconfname)"
  922. fi
  923. _debug httpdconf "$httpdconf"
  924. _debug httpdconfname "$httpdconfname"
  925. if [ ! -f "$httpdconf" ] ; then
  926. _err "Apache Config file not found" "$httpdconf"
  927. return 1
  928. fi
  929. return 0
  930. }
  931. _restoreApache() {
  932. if [ -z "$usingApache" ] ; then
  933. return 0
  934. fi
  935. _initpath
  936. if ! _apachePath ; then
  937. return 1
  938. fi
  939. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  940. _debug "No config file to restore."
  941. return 0
  942. fi
  943. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" > "$httpdconf"
  944. _debug "Restored: $httpdconf."
  945. if ! $_APAHECTL -t >/dev/null 2>&1 ; then
  946. _err "Sorry, restore apache config error, please contact me."
  947. return 1;
  948. fi
  949. _debug "Restored successfully."
  950. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  951. return 0
  952. }
  953. _setApache() {
  954. _initpath
  955. if ! _apachePath ; then
  956. return 1
  957. fi
  958. #test the conf first
  959. _info "Checking if there is an error in the apache config file before starting."
  960. _msg="$($_APAHECTL -t 2>&1 )"
  961. if [ "$?" != "0" ] ; then
  962. _err "Sorry, apache config file has error, please fix it first, then try again."
  963. _err "Don't worry, there is nothing changed to your system."
  964. _err "$_msg"
  965. return 1;
  966. else
  967. _info "OK"
  968. fi
  969. #backup the conf
  970. _debug "Backup apache config file" "$httpdconf"
  971. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/" ; then
  972. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  973. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  974. return 1
  975. fi
  976. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  977. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  978. _info "The backup file will be deleted on sucess, just forget it."
  979. #add alias
  980. apacheVer="$($_APAHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  981. _debug "apacheVer" "$apacheVer"
  982. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  983. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  984. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ] ; then
  985. echo "
  986. Alias /.well-known/acme-challenge $ACME_DIR
  987. <Directory $ACME_DIR >
  988. Require all granted
  989. </Directory>
  990. " >> "$httpdconf"
  991. else
  992. echo "
  993. Alias /.well-known/acme-challenge $ACME_DIR
  994. <Directory $ACME_DIR >
  995. Order allow,deny
  996. Allow from all
  997. </Directory>
  998. " >> "$httpdconf"
  999. fi
  1000. _msg="$($_APAHECTL -t 2>&1 )"
  1001. if [ "$?" != "0" ] ; then
  1002. _err "Sorry, apache config error"
  1003. if _restoreApache ; then
  1004. _err "The apache config file is restored."
  1005. else
  1006. _err "Sorry, The apache config file can not be restored, please report bug."
  1007. fi
  1008. return 1;
  1009. fi
  1010. if [ ! -d "$ACME_DIR" ] ; then
  1011. mkdir -p "$ACME_DIR"
  1012. chmod 755 "$ACME_DIR"
  1013. fi
  1014. if ! $_APAHECTL graceful ; then
  1015. _err "Sorry, $_APAHECTL graceful error, please contact me."
  1016. _restoreApache
  1017. return 1;
  1018. fi
  1019. usingApache="1"
  1020. return 0
  1021. }
  1022. _clearup() {
  1023. _stopserver $serverproc
  1024. serverproc=""
  1025. _restoreApache
  1026. if [ -z "$DEBUG" ] ; then
  1027. rm -f "$TLS_CONF"
  1028. rm -f "$TLS_CERT"
  1029. rm -f "$TLS_KEY"
  1030. rm -f "$TLS_CSR"
  1031. fi
  1032. }
  1033. # webroot removelevel tokenfile
  1034. _clearupwebbroot() {
  1035. __webroot="$1"
  1036. if [ -z "$__webroot" ] ; then
  1037. _debug "no webroot specified, skip"
  1038. return 0
  1039. fi
  1040. if [ "$2" = '1' ] ; then
  1041. _debug "remove $__webroot/.well-known"
  1042. rm -rf "$__webroot/.well-known"
  1043. elif [ "$2" = '2' ] ; then
  1044. _debug "remove $__webroot/.well-known/acme-challenge"
  1045. rm -rf "$__webroot/.well-known/acme-challenge"
  1046. elif [ "$2" = '3' ] ; then
  1047. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  1048. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  1049. else
  1050. _debug "Skip for removelevel:$2"
  1051. fi
  1052. return 0
  1053. }
  1054. issue() {
  1055. if [ -z "$2" ] ; then
  1056. echo "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  1057. return 1
  1058. fi
  1059. Le_Webroot="$1"
  1060. Le_Domain="$2"
  1061. Le_Alt="$3"
  1062. Le_Keylength="$4"
  1063. Le_RealCertPath="$5"
  1064. Le_RealKeyPath="$6"
  1065. Le_RealCACertPath="$7"
  1066. Le_ReloadCmd="$8"
  1067. Le_RealFullChainPath="$9"
  1068. #remove these later.
  1069. if [ "$Le_Webroot" = "dns-cf" ] ; then
  1070. Le_Webroot="dns_cf"
  1071. fi
  1072. if [ "$Le_Webroot" = "dns-dp" ] ; then
  1073. Le_Webroot="dns_dp"
  1074. fi
  1075. if [ "$Le_Webroot" = "dns-cx" ] ; then
  1076. Le_Webroot="dns_cx"
  1077. fi
  1078. _initpath $Le_Domain
  1079. if [ -f "$DOMAIN_CONF" ] ; then
  1080. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2 | tr -d "'\"")
  1081. _debug Le_NextRenewTime "$Le_NextRenewTime"
  1082. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ $(date -u "+%s" ) -lt $Le_NextRenewTime ] ; then
  1083. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  1084. return $RENEW_SKIP
  1085. fi
  1086. fi
  1087. _savedomainconf "Le_Domain" "$Le_Domain"
  1088. _savedomainconf "Le_Alt" "$Le_Alt"
  1089. _savedomainconf "Le_Webroot" "$Le_Webroot"
  1090. _savedomainconf "Le_Keylength" "$Le_Keylength"
  1091. if [ "$Le_Alt" = "no" ] ; then
  1092. Le_Alt=""
  1093. fi
  1094. if [ "$Le_Keylength" = "no" ] ; then
  1095. Le_Keylength=""
  1096. fi
  1097. if _hasfield "$Le_Webroot" "no" ; then
  1098. _info "Standalone mode."
  1099. if ! _exists "nc" ; then
  1100. _err "Please install netcat(nc) tools first."
  1101. return 1
  1102. fi
  1103. if [ -z "$Le_HTTPPort" ] ; then
  1104. Le_HTTPPort=80
  1105. else
  1106. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  1107. fi
  1108. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  1109. if [ "$netprc" ] ; then
  1110. _err "$netprc"
  1111. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  1112. _err "Please stop it first"
  1113. return 1
  1114. fi
  1115. fi
  1116. if _hasfield "$Le_Webroot" "$W_TLS" ; then
  1117. _info "Standalone tls mode."
  1118. if [ -z "$Le_TLSPort" ] ; then
  1119. Le_TLSPort=443
  1120. else
  1121. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  1122. fi
  1123. netprc="$(_ss "$Le_TLSPort" | grep "$Le_TLSPort")"
  1124. if [ "$netprc" ] ; then
  1125. _err "$netprc"
  1126. _err "tcp port $Le_TLSPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  1127. _err "Please stop it first"
  1128. return 1
  1129. fi
  1130. fi
  1131. if _hasfield "$Le_Webroot" "apache" ; then
  1132. if ! _setApache ; then
  1133. _err "set up apache error. Report error to me."
  1134. return 1
  1135. fi
  1136. else
  1137. usingApache=""
  1138. fi
  1139. if [ ! -f "$ACCOUNT_KEY_PATH" ] ; then
  1140. if ! createAccountKey $Le_Domain $Le_Keylength ; then
  1141. _err "Create account key error."
  1142. if [ "$usingApache" ] ; then
  1143. _restoreApache
  1144. fi
  1145. return 1
  1146. fi
  1147. fi
  1148. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  1149. if [ "$usingApache" ] ; then
  1150. _restoreApache
  1151. fi
  1152. return 1
  1153. fi
  1154. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  1155. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  1156. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  1157. accountkeyhash="$(echo $accountkeyhash$API | _digest "sha256" )"
  1158. if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
  1159. _info "Registering account"
  1160. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  1161. if [ "$ACCOUNT_EMAIL" ] ; then
  1162. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  1163. fi
  1164. _send_signed_request "$API/acme/new-reg" "$regjson"
  1165. if [ "$code" = "" ] || [ "$code" = '201' ] ; then
  1166. _info "Registered"
  1167. echo $response > $LE_WORKING_DIR/account.json
  1168. elif [ "$code" = '409' ] ; then
  1169. _info "Already registered"
  1170. else
  1171. _err "Register account Error: $response"
  1172. _clearup
  1173. return 1
  1174. fi
  1175. ACCOUNT_KEY_HASH="$accountkeyhash"
  1176. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  1177. else
  1178. _info "Skip register account key"
  1179. fi
  1180. if [ ! -f "$CERT_KEY_PATH" ] ; then
  1181. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  1182. _err "Create domain key error."
  1183. _clearup
  1184. return 1
  1185. fi
  1186. fi
  1187. if ! createCSR $Le_Domain $Le_Alt ; then
  1188. _err "Create CSR error."
  1189. _clearup
  1190. return 1
  1191. fi
  1192. vlist="$Le_Vlist"
  1193. # verify each domain
  1194. _info "Verify each domain"
  1195. sep='#'
  1196. if [ -z "$vlist" ] ; then
  1197. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  1198. _index=1
  1199. _currentRoot=""
  1200. for d in $alldomains
  1201. do
  1202. _info "Getting webroot for domain" $d
  1203. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  1204. _debug _w "$_w"
  1205. if [ "$_w" ] ; then
  1206. _currentRoot="$_w"
  1207. fi
  1208. _debug "_currentRoot" "$_currentRoot"
  1209. _index=$(_math $_index + 1)
  1210. vtype="$VTYPE_HTTP"
  1211. if _startswith "$_currentRoot" "dns" ; then
  1212. vtype="$VTYPE_DNS"
  1213. fi
  1214. if [ "$_currentRoot" = "$W_TLS" ] ; then
  1215. vtype="$VTYPE_TLS"
  1216. fi
  1217. _info "Getting token for domain" $d
  1218. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}" ; then
  1219. _err "Can not get domain token."
  1220. _clearup
  1221. return 1
  1222. fi
  1223. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  1224. _err "new-authz error: $response"
  1225. _clearup
  1226. return 1
  1227. fi
  1228. entry="$(printf "$response" | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  1229. _debug entry "$entry"
  1230. if [ -z "$entry" ] ; then
  1231. _err "Error, can not get domain token $d"
  1232. _clearup
  1233. return 1
  1234. fi
  1235. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  1236. _debug token $token
  1237. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  1238. _debug uri $uri
  1239. keyauthorization="$token.$thumbprint"
  1240. _debug keyauthorization "$keyauthorization"
  1241. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  1242. _debug dvlist "$dvlist"
  1243. vlist="$vlist$dvlist,"
  1244. done
  1245. #add entry
  1246. dnsadded=""
  1247. ventries=$(echo "$vlist" | tr ',' ' ' )
  1248. for ventry in $ventries
  1249. do
  1250. d=$(echo $ventry | cut -d $sep -f 1)
  1251. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1252. vtype=$(echo $ventry | cut -d $sep -f 4)
  1253. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1254. if [ "$vtype" = "$VTYPE_DNS" ] ; then
  1255. dnsadded='0'
  1256. txtdomain="_acme-challenge.$d"
  1257. _debug txtdomain "$txtdomain"
  1258. txt="$(echo -n $keyauthorization | _digest "sha256" | _urlencode)"
  1259. _debug txt "$txt"
  1260. #dns
  1261. #1. check use api
  1262. d_api=""
  1263. if [ -f "$LE_WORKING_DIR/$d/$_currentRoot" ] ; then
  1264. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  1265. elif [ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ] ; then
  1266. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  1267. elif [ -f "$LE_WORKING_DIR/$_currentRoot" ] ; then
  1268. d_api="$LE_WORKING_DIR/$_currentRoot"
  1269. elif [ -f "$LE_WORKING_DIR/$_currentRoot.sh" ] ; then
  1270. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  1271. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ] ; then
  1272. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  1273. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ] ; then
  1274. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  1275. fi
  1276. _debug d_api "$d_api"
  1277. if [ "$d_api" ] ; then
  1278. _info "Found domain api file: $d_api"
  1279. else
  1280. _err "Add the following TXT record:"
  1281. _err "Domain: $txtdomain"
  1282. _err "TXT value: $txt"
  1283. _err "Please be aware that you prepend _acme-challenge. before your domain"
  1284. _err "so the resulting subdomain will be: $txtdomain"
  1285. continue
  1286. fi
  1287. (
  1288. if ! . $d_api ; then
  1289. _err "Load file $d_api error. Please check your api file and try again."
  1290. return 1
  1291. fi
  1292. addcommand="${_currentRoot}_add"
  1293. if ! _exists $addcommand ; then
  1294. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1295. return 1
  1296. fi
  1297. if ! $addcommand $txtdomain $txt ; then
  1298. _err "Error add txt for domain:$txtdomain"
  1299. return 1
  1300. fi
  1301. )
  1302. if [ "$?" != "0" ] ; then
  1303. _clearup
  1304. return 1
  1305. fi
  1306. dnsadded='1'
  1307. fi
  1308. done
  1309. if [ "$dnsadded" = '0' ] ; then
  1310. _savedomainconf "Le_Vlist" "$vlist"
  1311. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1312. _err "Please add the TXT records to the domains, and retry again."
  1313. _clearup
  1314. return 1
  1315. fi
  1316. fi
  1317. if [ "$dnsadded" = '1' ] ; then
  1318. if [ -z "$Le_DNSSleep" ] ; then
  1319. Le_DNSSleep=60
  1320. else
  1321. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  1322. fi
  1323. _info "Sleep $Le_DNSSleep seconds for the txt records to take effect"
  1324. sleep $Le_DNSSleep
  1325. fi
  1326. _debug "ok, let's start to verify"
  1327. ventries=$(echo "$vlist" | tr ',' ' ' )
  1328. for ventry in $ventries
  1329. do
  1330. d=$(echo $ventry | cut -d $sep -f 1)
  1331. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1332. uri=$(echo $ventry | cut -d $sep -f 3)
  1333. vtype=$(echo $ventry | cut -d $sep -f 4)
  1334. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1335. _info "Verifying:$d"
  1336. _debug "d" "$d"
  1337. _debug "keyauthorization" "$keyauthorization"
  1338. _debug "uri" "$uri"
  1339. removelevel=""
  1340. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  1341. _debug "_currentRoot" "$_currentRoot"
  1342. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1343. if [ "$_currentRoot" = "no" ] ; then
  1344. _info "Standalone mode server"
  1345. _startserver "$keyauthorization" &
  1346. if [ "$?" != "0" ] ; then
  1347. _clearup
  1348. return 1
  1349. fi
  1350. serverproc="$!"
  1351. sleep 2
  1352. _debug serverproc $serverproc
  1353. else
  1354. if [ "$_currentRoot" = "apache" ] ; then
  1355. wellknown_path="$ACME_DIR"
  1356. else
  1357. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1358. if [ ! -d "$_currentRoot/.well-known" ] ; then
  1359. removelevel='1'
  1360. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ] ; then
  1361. removelevel='2'
  1362. else
  1363. removelevel='3'
  1364. fi
  1365. fi
  1366. _debug wellknown_path "$wellknown_path"
  1367. _debug "writing token:$token to $wellknown_path/$token"
  1368. mkdir -p "$wellknown_path"
  1369. printf "%s" "$keyauthorization" > "$wellknown_path/$token"
  1370. if [ ! "$usingApache" ] ; then
  1371. webroot_owner=$(_stat $_currentRoot)
  1372. _debug "Changing owner/group of .well-known to $webroot_owner"
  1373. chown -R $webroot_owner "$_currentRoot/.well-known"
  1374. fi
  1375. fi
  1376. elif [ "$vtype" = "$VTYPE_TLS" ] ; then
  1377. #create A
  1378. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  1379. #_debug2 _hash_A "$_hash_A"
  1380. #_x="$(echo $_hash_A | cut -c 1-32)"
  1381. #_debug2 _x "$_x"
  1382. #_y="$(echo $_hash_A | cut -c 33-64)"
  1383. #_debug2 _y "$_y"
  1384. #_SAN_A="$_x.$_y.token.acme.invalid"
  1385. #_debug2 _SAN_A "$_SAN_A"
  1386. #create B
  1387. _hash_B="$(printf "%s" $keyauthorization | _digest "sha256" "hex" )"
  1388. _debug2 _hash_B "$_hash_B"
  1389. _x="$(echo $_hash_B | cut -c 1-32)"
  1390. _debug2 _x "$_x"
  1391. _y="$(echo $_hash_B | cut -c 33-64)"
  1392. _debug2 _y "$_y"
  1393. #_SAN_B="$_x.$_y.ka.acme.invalid"
  1394. _SAN_B="$_x.$_y.acme.invalid"
  1395. _debug2 _SAN_B "$_SAN_B"
  1396. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" ; then
  1397. _err "Start tls server error."
  1398. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1399. _clearup
  1400. return 1
  1401. fi
  1402. fi
  1403. if ! _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}" ; then
  1404. _err "$d:Can not get challenge: $response"
  1405. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1406. _clearup
  1407. return 1
  1408. fi
  1409. if [ ! -z "$code" ] && [ ! "$code" = '202' ] ; then
  1410. _err "$d:Challenge error: $response"
  1411. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1412. _clearup
  1413. return 1
  1414. fi
  1415. waittimes=0
  1416. if [ -z "$MAX_RETRY_TIMES" ] ; then
  1417. MAX_RETRY_TIMES=30
  1418. fi
  1419. while true ; do
  1420. waittimes=$(_math $waittimes + 1)
  1421. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ] ; then
  1422. _err "$d:Timeout"
  1423. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1424. _clearup
  1425. return 1
  1426. fi
  1427. _debug "sleep 5 secs to verify"
  1428. sleep 5
  1429. _debug "checking"
  1430. response="$(_get $uri)"
  1431. if [ "$?" != "0" ] ; then
  1432. _err "$d:Verify error:$response"
  1433. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1434. _clearup
  1435. return 1
  1436. fi
  1437. _debug2 original "$response"
  1438. response="$(echo "$response" | _normalizeJson )"
  1439. _debug2 response "$response"
  1440. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  1441. if [ "$status" = "valid" ] ; then
  1442. _info "Success"
  1443. _stopserver $serverproc
  1444. serverproc=""
  1445. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1446. break;
  1447. fi
  1448. if [ "$status" = "invalid" ] ; then
  1449. error="$(echo $response | tr -d "\r\n" | egrep -o '"error":{[^}]*}')"
  1450. _debug2 error "$error"
  1451. errordetail="$(echo $error | grep -o '"detail": *"[^"]*"' | cut -d '"' -f 4)"
  1452. _debug2 errordetail "$errordetail"
  1453. if [ "$errordetail" ] ; then
  1454. _err "$d:Verify error:$errordetail"
  1455. else
  1456. _err "$d:Verify error:$error"
  1457. fi
  1458. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1459. _clearup
  1460. return 1;
  1461. fi
  1462. if [ "$status" = "pending" ] ; then
  1463. _info "Pending"
  1464. else
  1465. _err "$d:Verify error:$response"
  1466. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1467. _clearup
  1468. return 1
  1469. fi
  1470. done
  1471. done
  1472. _clearup
  1473. _info "Verify finished, start to sign."
  1474. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1475. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64" ; then
  1476. _err "Sign failed."
  1477. return 1
  1478. fi
  1479. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1480. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  1481. if [ "$Le_LinkCert" ] ; then
  1482. echo "$BEGIN_CERT" > "$CERT_PATH"
  1483. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1484. echo "$END_CERT" >> "$CERT_PATH"
  1485. _info "Cert success."
  1486. cat "$CERT_PATH"
  1487. _info "Your cert is in $CERT_PATH"
  1488. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1489. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ] ; then
  1490. USER_PATH="$PATH"
  1491. _saveaccountconf "USER_PATH" "$USER_PATH"
  1492. fi
  1493. fi
  1494. if [ -z "$Le_LinkCert" ] ; then
  1495. response="$(echo $response | _dbase64 "multiline" | _normalizeJson )"
  1496. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1497. return 1
  1498. fi
  1499. _cleardomainconf "Le_Vlist"
  1500. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1501. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  1502. if [ "$Le_LinkIssuer" ] ; then
  1503. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1504. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1505. echo "$END_CERT" >> "$CA_CERT_PATH"
  1506. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1507. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1508. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1509. fi
  1510. Le_CertCreateTime=$(date -u "+%s")
  1511. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  1512. Le_CertCreateTimeStr=$(date -u )
  1513. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  1514. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ] ; then
  1515. Le_RenewalDays=$MAX_RENEW
  1516. else
  1517. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  1518. fi
  1519. if [ "$Le_Insecure" ] ; then
  1520. _savedomainconf "Le_Insecure" "$Le_Insecure"
  1521. fi
  1522. Le_NextRenewTime=$(_math $Le_CertCreateTime + $Le_RenewalDays \* 24 \* 60 \* 60)
  1523. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  1524. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1525. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  1526. _output="$(installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" 2>&1)"
  1527. _ret="$?"
  1528. if [ "$_ret" = "9" ] ; then
  1529. #ignore the empty install error.
  1530. return 0
  1531. fi
  1532. if [ "$_ret" != "0" ] ; then
  1533. _err "$_output"
  1534. return 1
  1535. fi
  1536. }
  1537. renew() {
  1538. Le_Domain="$1"
  1539. if [ -z "$Le_Domain" ] ; then
  1540. _err "Usage: $PROJECT_ENTRY --renew -d domain.com"
  1541. return 1
  1542. fi
  1543. _initpath $Le_Domain
  1544. _info "Renew: $Le_Domain"
  1545. if [ ! -f "$DOMAIN_CONF" ] ; then
  1546. _info "$Le_Domain is not a issued domain, skip."
  1547. return 0;
  1548. fi
  1549. . "$DOMAIN_CONF"
  1550. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  1551. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1552. return $RENEW_SKIP
  1553. fi
  1554. IS_RENEW="1"
  1555. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1556. local res=$?
  1557. IS_RENEW=""
  1558. return $res
  1559. }
  1560. #renewAll [stopRenewOnError]
  1561. renewAll() {
  1562. _initpath
  1563. _stopRenewOnError="$1"
  1564. _debug "_stopRenewOnError" "$_stopRenewOnError"
  1565. _ret="0"
  1566. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1567. d=$(echo $d | cut -d '/' -f 1)
  1568. (
  1569. renew "$d"
  1570. )
  1571. rc="$?"
  1572. _debug "Return code: $rc"
  1573. if [ "$rc" != "0" ] ; then
  1574. if [ "$rc" = "$RENEW_SKIP" ] ; then
  1575. _info "Skipped $d"
  1576. elif [ "$_stopRenewOnError" ] ; then
  1577. _err "Error renew $d, stop now."
  1578. return $rc
  1579. else
  1580. _ret="$rc"
  1581. _err "Error renew $d, Go ahead to next one."
  1582. fi
  1583. fi
  1584. done
  1585. return $_ret
  1586. }
  1587. list() {
  1588. local _raw="$1"
  1589. _initpath
  1590. _sep="|"
  1591. if [ "$_raw" ] ; then
  1592. printf "Main_Domain${_sep}SAN_Domains${_sep}Created${_sep}Renew\n"
  1593. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1594. d=$(echo $d | cut -d '/' -f 1)
  1595. (
  1596. _initpath $d
  1597. if [ -f "$DOMAIN_CONF" ] ; then
  1598. . "$DOMAIN_CONF"
  1599. printf "$Le_Domain${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr\n"
  1600. fi
  1601. )
  1602. done
  1603. else
  1604. list "raw" | column -t -s "$_sep"
  1605. fi
  1606. }
  1607. installcert() {
  1608. Le_Domain="$1"
  1609. if [ -z "$Le_Domain" ] ; then
  1610. echo "Usage: $PROJECT_ENTRY --installcert -d domain.com [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  1611. return 1
  1612. fi
  1613. Le_RealCertPath="$2"
  1614. Le_RealKeyPath="$3"
  1615. Le_RealCACertPath="$4"
  1616. Le_ReloadCmd="$5"
  1617. Le_RealFullChainPath="$6"
  1618. _initpath $Le_Domain
  1619. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  1620. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  1621. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  1622. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  1623. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  1624. if [ "$Le_RealCertPath" = "no" ] ; then
  1625. Le_RealCertPath=""
  1626. fi
  1627. if [ "$Le_RealKeyPath" = "no" ] ; then
  1628. Le_RealKeyPath=""
  1629. fi
  1630. if [ "$Le_RealCACertPath" = "no" ] ; then
  1631. Le_RealCACertPath=""
  1632. fi
  1633. if [ "$Le_ReloadCmd" = "no" ] ; then
  1634. Le_ReloadCmd=""
  1635. fi
  1636. if [ "$Le_RealFullChainPath" = "no" ] ; then
  1637. Le_RealFullChainPath=""
  1638. fi
  1639. _installed="0"
  1640. if [ "$Le_RealCertPath" ] ; then
  1641. _installed=1
  1642. _info "Installing cert to:$Le_RealCertPath"
  1643. if [ -f "$Le_RealCertPath" ] ; then
  1644. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  1645. fi
  1646. cat "$CERT_PATH" > "$Le_RealCertPath"
  1647. fi
  1648. if [ "$Le_RealCACertPath" ] ; then
  1649. _installed=1
  1650. _info "Installing CA to:$Le_RealCACertPath"
  1651. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ] ; then
  1652. echo "" >> "$Le_RealCACertPath"
  1653. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1654. else
  1655. if [ -f "$Le_RealCACertPath" ] ; then
  1656. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1657. fi
  1658. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1659. fi
  1660. fi
  1661. if [ "$Le_RealKeyPath" ] ; then
  1662. _installed=1
  1663. _info "Installing key to:$Le_RealKeyPath"
  1664. if [ -f "$Le_RealKeyPath" ] ; then
  1665. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1666. fi
  1667. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1668. fi
  1669. if [ "$Le_RealFullChainPath" ] ; then
  1670. _installed=1
  1671. _info "Installing full chain to:$Le_RealFullChainPath"
  1672. if [ -f "$Le_RealFullChainPath" ] ; then
  1673. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  1674. fi
  1675. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  1676. fi
  1677. if [ "$Le_ReloadCmd" ] ; then
  1678. _installed=1
  1679. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1680. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd") ; then
  1681. _info "Reload success."
  1682. else
  1683. _err "Reload error for :$Le_Domain"
  1684. fi
  1685. fi
  1686. if [ "$_installed" = "0" ] ; then
  1687. _err "Nothing to install. You don't specify any parameter."
  1688. return 9
  1689. fi
  1690. }
  1691. installcronjob() {
  1692. _initpath
  1693. if ! _exists "crontab" ; then
  1694. _err "crontab doesn't exist, so, we can not install cron jobs."
  1695. _err "All your certs will not be renewed automatically."
  1696. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  1697. return 1
  1698. fi
  1699. _info "Installing cron job"
  1700. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  1701. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ] ; then
  1702. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  1703. else
  1704. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  1705. return 1
  1706. fi
  1707. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  1708. fi
  1709. if [ "$?" != "0" ] ; then
  1710. _err "Install cron job failed. You need to manually renew your certs."
  1711. _err "Or you can add cronjob by yourself:"
  1712. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  1713. return 1
  1714. fi
  1715. }
  1716. uninstallcronjob() {
  1717. if ! _exists "crontab" ; then
  1718. return
  1719. fi
  1720. _info "Removing cron job"
  1721. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  1722. if [ "$cr" ] ; then
  1723. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  1724. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  1725. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1726. fi
  1727. _initpath
  1728. }
  1729. revoke() {
  1730. Le_Domain="$1"
  1731. if [ -z "$Le_Domain" ] ; then
  1732. echo "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  1733. return 1
  1734. fi
  1735. _initpath $Le_Domain
  1736. if [ ! -f "$DOMAIN_CONF" ] ; then
  1737. _err "$Le_Domain is not a issued domain, skip."
  1738. return 1;
  1739. fi
  1740. if [ ! -f "$CERT_PATH" ] ; then
  1741. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  1742. return 1
  1743. fi
  1744. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  1745. if [ -z "$cert" ] ; then
  1746. _err "Cert for $Le_Domain is empty found, skip."
  1747. return 1
  1748. fi
  1749. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  1750. uri="$API/acme/revoke-cert"
  1751. _info "Try domain key first."
  1752. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  1753. if [ -z "$response" ] ; then
  1754. _info "Revoke success."
  1755. rm -f $CERT_PATH
  1756. return 0
  1757. else
  1758. _err "Revoke error by domain key."
  1759. _err "$resource"
  1760. fi
  1761. fi
  1762. _info "Then try account key."
  1763. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  1764. if [ -z "$response" ] ; then
  1765. _info "Revoke success."
  1766. rm -f $CERT_PATH
  1767. return 0
  1768. else
  1769. _err "Revoke error."
  1770. _debug "$resource"
  1771. fi
  1772. fi
  1773. return 1
  1774. }
  1775. # Detect profile file if not specified as environment variable
  1776. _detect_profile() {
  1777. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  1778. echo "$PROFILE"
  1779. return
  1780. fi
  1781. local DETECTED_PROFILE
  1782. DETECTED_PROFILE=''
  1783. local SHELLTYPE
  1784. SHELLTYPE="$(basename "/$SHELL")"
  1785. if [ "$SHELLTYPE" = "bash" ] ; then
  1786. if [ -f "$HOME/.bashrc" ] ; then
  1787. DETECTED_PROFILE="$HOME/.bashrc"
  1788. elif [ -f "$HOME/.bash_profile" ] ; then
  1789. DETECTED_PROFILE="$HOME/.bash_profile"
  1790. fi
  1791. elif [ "$SHELLTYPE" = "zsh" ] ; then
  1792. DETECTED_PROFILE="$HOME/.zshrc"
  1793. fi
  1794. if [ -z "$DETECTED_PROFILE" ] ; then
  1795. if [ -f "$HOME/.profile" ] ; then
  1796. DETECTED_PROFILE="$HOME/.profile"
  1797. elif [ -f "$HOME/.bashrc" ] ; then
  1798. DETECTED_PROFILE="$HOME/.bashrc"
  1799. elif [ -f "$HOME/.bash_profile" ] ; then
  1800. DETECTED_PROFILE="$HOME/.bash_profile"
  1801. elif [ -f "$HOME/.zshrc" ] ; then
  1802. DETECTED_PROFILE="$HOME/.zshrc"
  1803. fi
  1804. fi
  1805. if [ ! -z "$DETECTED_PROFILE" ] ; then
  1806. echo "$DETECTED_PROFILE"
  1807. fi
  1808. }
  1809. _initconf() {
  1810. _initpath
  1811. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1812. echo "#ACCOUNT_CONF_PATH=xxxx
  1813. #Account configurations:
  1814. #Here are the supported macros, uncomment them to make them take effect.
  1815. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1816. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1817. #CERT_HOME=\"/path/to/cert/home\"
  1818. #STAGE=1 # Use the staging api
  1819. #FORCE=1 # Force to issue cert
  1820. #DEBUG=1 # Debug mode
  1821. #ACCOUNT_KEY_HASH=account key hash
  1822. #USER_AGENT=\"$USER_AGENT\"
  1823. #USER_PATH=""
  1824. #dns api
  1825. #######################
  1826. #Cloudflare:
  1827. #api key
  1828. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1829. #account email
  1830. #CF_Email=\"xxxx@sss.com\"
  1831. #######################
  1832. #Dnspod.cn:
  1833. #api key id
  1834. #DP_Id=\"1234\"
  1835. #api key
  1836. #DP_Key=\"sADDsdasdgdsf\"
  1837. #######################
  1838. #Cloudxns.com:
  1839. #CX_Key=\"1234\"
  1840. #
  1841. #CX_Secret=\"sADDsdasdgdsf\"
  1842. " > $ACCOUNT_CONF_PATH
  1843. fi
  1844. }
  1845. # nocron
  1846. _precheck() {
  1847. _nocron="$1"
  1848. if ! _exists "curl" && ! _exists "wget"; then
  1849. _err "Please install curl or wget first, we need to access http resources."
  1850. return 1
  1851. fi
  1852. if [ -z "$_nocron" ] ; then
  1853. if ! _exists "crontab" ; then
  1854. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1855. _err "We need to set cron job to renew the certs automatically."
  1856. _err "Otherwise, your certs will not be able to be renewed automatically."
  1857. if [ -z "$FORCE" ] ; then
  1858. _err "Please add '--force' and try install again to go without crontab."
  1859. _err "./$PROJECT_ENTRY --install --force"
  1860. return 1
  1861. fi
  1862. fi
  1863. fi
  1864. if ! _exists "openssl" ; then
  1865. _err "Please install openssl first."
  1866. _err "We need openssl to generate keys."
  1867. return 1
  1868. fi
  1869. if ! _exists "nc" ; then
  1870. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1871. _err "We use nc for standalone server if you use standalone mode."
  1872. _err "If you don't use standalone mode, just ignore this warning."
  1873. fi
  1874. return 0
  1875. }
  1876. _setShebang() {
  1877. _file="$1"
  1878. _shebang="$2"
  1879. if [ -z "$_shebang" ] ; then
  1880. _err "Usage: file shebang"
  1881. return 1
  1882. fi
  1883. cp "$_file" "$_file.tmp"
  1884. echo "$_shebang" > "$_file"
  1885. sed -n 2,99999p "$_file.tmp" >> "$_file"
  1886. rm -f "$_file.tmp"
  1887. }
  1888. _installalias() {
  1889. _initpath
  1890. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1891. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ] ; then
  1892. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  1893. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  1894. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  1895. fi
  1896. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  1897. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1898. _profile="$(_detect_profile)"
  1899. if [ "$_profile" ] ; then
  1900. _debug "Found profile: $_profile"
  1901. _setopt "$_profile" ". \"$_envfile\""
  1902. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  1903. else
  1904. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  1905. fi
  1906. #for csh
  1907. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  1908. _csh_profile="$HOME/.cshrc"
  1909. if [ -f "$_csh_profile" ] ; then
  1910. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  1911. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1912. _setopt "$_csh_profile" "source \"$_cshfile\""
  1913. fi
  1914. #for tcsh
  1915. _tcsh_profile="$HOME/.tcshrc"
  1916. if [ -f "$_tcsh_profile" ] ; then
  1917. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  1918. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1919. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  1920. fi
  1921. }
  1922. # nocron
  1923. install() {
  1924. _nocron="$1"
  1925. if ! _initpath ; then
  1926. _err "Install failed."
  1927. return 1
  1928. fi
  1929. if [ "$_nocron" ] ; then
  1930. _debug "Skip install cron job"
  1931. fi
  1932. if ! _precheck "$_nocron" ; then
  1933. _err "Pre-check failed, can not install."
  1934. return 1
  1935. fi
  1936. #convert from le
  1937. if [ -d "$HOME/.le" ] ; then
  1938. for envfile in "le.env" "le.sh.env"
  1939. do
  1940. if [ -f "$HOME/.le/$envfile" ] ; then
  1941. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  1942. _upgrading="1"
  1943. _info "You are upgrading from le.sh"
  1944. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  1945. mv "$HOME/.le" "$LE_WORKING_DIR"
  1946. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1947. break;
  1948. fi
  1949. fi
  1950. done
  1951. fi
  1952. _info "Installing to $LE_WORKING_DIR"
  1953. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1954. _err "Can not create working dir: $LE_WORKING_DIR"
  1955. return 1
  1956. fi
  1957. chmod 700 "$LE_WORKING_DIR"
  1958. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  1959. if [ "$?" != "0" ] ; then
  1960. _err "Install failed, can not copy $PROJECT_ENTRY"
  1961. return 1
  1962. fi
  1963. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  1964. _installalias
  1965. if [ -d "dnsapi" ] ; then
  1966. mkdir -p $LE_WORKING_DIR/dnsapi
  1967. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1968. fi
  1969. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1970. _initconf
  1971. fi
  1972. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ] ; then
  1973. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  1974. fi
  1975. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ] ; then
  1976. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  1977. fi
  1978. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ] ; then
  1979. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  1980. fi
  1981. if [ -z "$_nocron" ] ; then
  1982. installcronjob
  1983. fi
  1984. if [ -z "$NO_DETECT_SH" ] ; then
  1985. #Modify shebang
  1986. if _exists bash ; then
  1987. _info "Good, bash is installed, change the shebang to use bash as prefered."
  1988. _shebang='#!/usr/bin/env bash'
  1989. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  1990. if [ -d "$LE_WORKING_DIR/dnsapi" ] ; then
  1991. for _apifile in $(ls "$LE_WORKING_DIR/dnsapi/"*.sh) ; do
  1992. _setShebang "$_apifile" "$_shebang"
  1993. done
  1994. fi
  1995. fi
  1996. fi
  1997. _info OK
  1998. }
  1999. # nocron
  2000. uninstall() {
  2001. _nocron="$1"
  2002. if [ -z "$_nocron" ] ; then
  2003. uninstallcronjob
  2004. fi
  2005. _initpath
  2006. _profile="$(_detect_profile)"
  2007. if [ "$_profile" ] ; then
  2008. text="$(cat $_profile)"
  2009. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" > "$_profile"
  2010. fi
  2011. _csh_profile="$HOME/.cshrc"
  2012. if [ -f "$_csh_profile" ] ; then
  2013. text="$(cat $_csh_profile)"
  2014. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_csh_profile"
  2015. fi
  2016. _tcsh_profile="$HOME/.tcshrc"
  2017. if [ -f "$_tcsh_profile" ] ; then
  2018. text="$(cat $_tcsh_profile)"
  2019. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_tcsh_profile"
  2020. fi
  2021. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  2022. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  2023. }
  2024. cron() {
  2025. IN_CRON=1
  2026. renewAll
  2027. _ret="$?"
  2028. IN_CRON=""
  2029. return $_ret
  2030. }
  2031. version() {
  2032. echo "$PROJECT"
  2033. echo "v$VER"
  2034. }
  2035. showhelp() {
  2036. version
  2037. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  2038. Commands:
  2039. --help, -h Show this help message.
  2040. --version, -v Show version info.
  2041. --install Install $PROJECT_NAME to your system.
  2042. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  2043. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT
  2044. --issue Issue a cert.
  2045. --installcert Install the issued cert to apache/nginx or any other server.
  2046. --renew, -r Renew a cert.
  2047. --renewAll Renew all the certs
  2048. --revoke Revoke a cert.
  2049. --list List all the certs
  2050. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  2051. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  2052. --cron Run cron job to renew all the certs.
  2053. --toPkcs Export the certificate and key to a pfx file.
  2054. --createAccountKey, -cak Create an account private key, professional use.
  2055. --createDomainKey, -cdk Create an domain private key, professional use.
  2056. --createCSR, -ccsr Create CSR , professional use.
  2057. Parameters:
  2058. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  2059. --force, -f Used to force to install or force to renew a cert immediately.
  2060. --staging, --test Use staging server, just for test.
  2061. --debug Output debug info.
  2062. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  2063. --standalone Use standalone mode.
  2064. --tls Use standalone tls mode.
  2065. --apache Use apache mode.
  2066. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  2067. --dnssleep [60] The time in seconds to wait for all the txt records to take effect in dns api mode. Default 60 seconds.
  2068. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  2069. --accountkeylength, -ak [2048] Specifies the account key length.
  2070. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  2071. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  2072. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  2073. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  2074. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  2075. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  2076. --accountconf Specifies a customized account config file.
  2077. --home Specifies the home dir for $PROJECT_NAME .
  2078. --certhome Specifies the home dir to save all the certs, only valid for '--install' command.
  2079. --useragent Specifies the user agent string. it will be saved for future use too.
  2080. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  2081. --accountkey Specifies the account key path, Only valid for the '--install' command.
  2082. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  2083. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  2084. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  2085. --listraw Only used for '--list' command, list the certs in raw format.
  2086. --stopRenewOnError, -se Only valid for '--renewall' command. Stop if one cert has error in renewal.
  2087. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  2088. --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
  2089. "
  2090. }
  2091. # nocron
  2092. _installOnline() {
  2093. _info "Installing from online archive."
  2094. _nocron="$1"
  2095. if [ ! "$BRANCH" ] ; then
  2096. BRANCH="master"
  2097. fi
  2098. _initpath
  2099. target="$PROJECT/archive/$BRANCH.tar.gz"
  2100. _info "Downloading $target"
  2101. localname="$BRANCH.tar.gz"
  2102. if ! _get "$target" > $localname ; then
  2103. _debug "Download error."
  2104. return 1
  2105. fi
  2106. _info "Extracting $localname"
  2107. tar xzf $localname
  2108. cd "$PROJECT_NAME-$BRANCH"
  2109. chmod +x $PROJECT_ENTRY
  2110. if ./$PROJECT_ENTRY install "$_nocron" ; then
  2111. _info "Install success!"
  2112. fi
  2113. cd ..
  2114. rm -rf "$PROJECT_NAME-$BRANCH"
  2115. rm -f "$localname"
  2116. }
  2117. upgrade() {
  2118. if (
  2119. cd $LE_WORKING_DIR
  2120. _installOnline "nocron"
  2121. ) ; then
  2122. _info "Upgrade success!"
  2123. else
  2124. _err "Upgrade failed!"
  2125. fi
  2126. }
  2127. _process() {
  2128. _CMD=""
  2129. _domain=""
  2130. _altdomains="no"
  2131. _webroot=""
  2132. _keylength="no"
  2133. _accountkeylength="no"
  2134. _certpath="no"
  2135. _keypath="no"
  2136. _capath="no"
  2137. _fullchainpath="no"
  2138. _reloadcmd=""
  2139. _password=""
  2140. _accountconf=""
  2141. _useragent=""
  2142. _accountemail=""
  2143. _accountkey=""
  2144. _certhome=""
  2145. _httpport=""
  2146. _tlsport=""
  2147. _dnssleep=""
  2148. _listraw=""
  2149. _stopRenewOnError=""
  2150. _insecure=""
  2151. _nocron=""
  2152. while [ ${#} -gt 0 ] ; do
  2153. case "${1}" in
  2154. --help|-h)
  2155. showhelp
  2156. return
  2157. ;;
  2158. --version|-v)
  2159. version
  2160. return
  2161. ;;
  2162. --install)
  2163. _CMD="install"
  2164. ;;
  2165. --uninstall)
  2166. _CMD="uninstall"
  2167. ;;
  2168. --upgrade)
  2169. _CMD="upgrade"
  2170. ;;
  2171. --issue)
  2172. _CMD="issue"
  2173. ;;
  2174. --installcert|-i)
  2175. _CMD="installcert"
  2176. ;;
  2177. --renew|-r)
  2178. _CMD="renew"
  2179. ;;
  2180. --renewAll|--renewall)
  2181. _CMD="renewAll"
  2182. ;;
  2183. --revoke)
  2184. _CMD="revoke"
  2185. ;;
  2186. --list)
  2187. _CMD="list"
  2188. ;;
  2189. --installcronjob)
  2190. _CMD="installcronjob"
  2191. ;;
  2192. --uninstallcronjob)
  2193. _CMD="uninstallcronjob"
  2194. ;;
  2195. --cron)
  2196. _CMD="cron"
  2197. ;;
  2198. --toPkcs)
  2199. _CMD="toPkcs"
  2200. ;;
  2201. --createAccountKey|--createaccountkey|-cak)
  2202. _CMD="createAccountKey"
  2203. ;;
  2204. --createDomainKey|--createdomainkey|-cdk)
  2205. _CMD="createDomainKey"
  2206. ;;
  2207. --createCSR|--createcsr|-ccr)
  2208. _CMD="createCSR"
  2209. ;;
  2210. --domain|-d)
  2211. _dvalue="$2"
  2212. if [ "$_dvalue" ] ; then
  2213. if _startswith "$_dvalue" "-" ; then
  2214. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  2215. return 1
  2216. fi
  2217. if [ -z "$_domain" ] ; then
  2218. _domain="$_dvalue"
  2219. else
  2220. if [ "$_altdomains" = "no" ] ; then
  2221. _altdomains="$_dvalue"
  2222. else
  2223. _altdomains="$_altdomains,$_dvalue"
  2224. fi
  2225. fi
  2226. fi
  2227. shift
  2228. ;;
  2229. --force|-f)
  2230. FORCE="1"
  2231. ;;
  2232. --staging|--test)
  2233. STAGE="1"
  2234. ;;
  2235. --debug)
  2236. if [ -z "$2" ] || _startswith "$2" "-" ; then
  2237. DEBUG="1"
  2238. else
  2239. DEBUG="$2"
  2240. shift
  2241. fi
  2242. ;;
  2243. --webroot|-w)
  2244. wvalue="$2"
  2245. if [ -z "$_webroot" ] ; then
  2246. _webroot="$wvalue"
  2247. else
  2248. _webroot="$_webroot,$wvalue"
  2249. fi
  2250. shift
  2251. ;;
  2252. --standalone)
  2253. wvalue="no"
  2254. if [ -z "$_webroot" ] ; then
  2255. _webroot="$wvalue"
  2256. else
  2257. _webroot="$_webroot,$wvalue"
  2258. fi
  2259. ;;
  2260. --apache)
  2261. wvalue="apache"
  2262. if [ -z "$_webroot" ] ; then
  2263. _webroot="$wvalue"
  2264. else
  2265. _webroot="$_webroot,$wvalue"
  2266. fi
  2267. ;;
  2268. --tls)
  2269. wvalue="$W_TLS"
  2270. if [ -z "$_webroot" ] ; then
  2271. _webroot="$wvalue"
  2272. else
  2273. _webroot="$_webroot,$wvalue"
  2274. fi
  2275. ;;
  2276. --dns)
  2277. wvalue="dns"
  2278. if ! _startswith "$2" "-" ; then
  2279. wvalue="$2"
  2280. shift
  2281. fi
  2282. if [ -z "$_webroot" ] ; then
  2283. _webroot="$wvalue"
  2284. else
  2285. _webroot="$_webroot,$wvalue"
  2286. fi
  2287. ;;
  2288. --dnssleep)
  2289. _dnssleep="$2"
  2290. Le_DNSSleep="$_dnssleep"
  2291. shift
  2292. ;;
  2293. --keylength|-k)
  2294. _keylength="$2"
  2295. if [ "$_accountkeylength" = "no" ] ; then
  2296. _accountkeylength="$2"
  2297. fi
  2298. shift
  2299. ;;
  2300. --accountkeylength|-ak)
  2301. _accountkeylength="$2"
  2302. shift
  2303. ;;
  2304. --certpath)
  2305. _certpath="$2"
  2306. shift
  2307. ;;
  2308. --keypath)
  2309. _keypath="$2"
  2310. shift
  2311. ;;
  2312. --capath)
  2313. _capath="$2"
  2314. shift
  2315. ;;
  2316. --fullchainpath)
  2317. _fullchainpath="$2"
  2318. shift
  2319. ;;
  2320. --reloadcmd|--reloadCmd)
  2321. _reloadcmd="$2"
  2322. shift
  2323. ;;
  2324. --password)
  2325. _password="$2"
  2326. shift
  2327. ;;
  2328. --accountconf)
  2329. _accountconf="$2"
  2330. ACCOUNT_CONF_PATH="$_accountconf"
  2331. shift
  2332. ;;
  2333. --home)
  2334. LE_WORKING_DIR="$2"
  2335. shift
  2336. ;;
  2337. --certhome)
  2338. _certhome="$2"
  2339. CERT_HOME="$_certhome"
  2340. shift
  2341. ;;
  2342. --useragent)
  2343. _useragent="$2"
  2344. USER_AGENT="$_useragent"
  2345. shift
  2346. ;;
  2347. --accountemail )
  2348. _accountemail="$2"
  2349. ACCOUNT_EMAIL="$_accountemail"
  2350. shift
  2351. ;;
  2352. --accountkey )
  2353. _accountkey="$2"
  2354. ACCOUNT_KEY_PATH="$_accountkey"
  2355. shift
  2356. ;;
  2357. --days )
  2358. _days="$2"
  2359. Le_RenewalDays="$_days"
  2360. shift
  2361. ;;
  2362. --httpport )
  2363. _httpport="$2"
  2364. Le_HTTPPort="$_httpport"
  2365. shift
  2366. ;;
  2367. --tlsport )
  2368. _tlsport="$2"
  2369. Le_TLSPort="$_tlsport"
  2370. shift
  2371. ;;
  2372. --listraw )
  2373. _listraw="raw"
  2374. ;;
  2375. --stopRenewOnError|--stoprenewonerror|-se )
  2376. _stopRenewOnError="1"
  2377. ;;
  2378. --insecure)
  2379. _insecure="1"
  2380. Le_Insecure="$_insecure"
  2381. ;;
  2382. --nocron)
  2383. _nocron="1"
  2384. ;;
  2385. *)
  2386. _err "Unknown parameter : $1"
  2387. return 1
  2388. ;;
  2389. esac
  2390. shift 1
  2391. done
  2392. case "${_CMD}" in
  2393. install) install "$_nocron" ;;
  2394. uninstall) uninstall "$_nocron" ;;
  2395. upgrade) upgrade ;;
  2396. issue)
  2397. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  2398. ;;
  2399. installcert)
  2400. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  2401. ;;
  2402. renew)
  2403. renew "$_domain"
  2404. ;;
  2405. renewAll)
  2406. renewAll "$_stopRenewOnError"
  2407. ;;
  2408. revoke)
  2409. revoke "$_domain"
  2410. ;;
  2411. list)
  2412. list "$_listraw"
  2413. ;;
  2414. installcronjob) installcronjob ;;
  2415. uninstallcronjob) uninstallcronjob ;;
  2416. cron) cron ;;
  2417. toPkcs)
  2418. toPkcs "$_domain" "$_password"
  2419. ;;
  2420. createAccountKey)
  2421. createAccountKey "$_domain" "$_accountkeylength"
  2422. ;;
  2423. createDomainKey)
  2424. createDomainKey "$_domain" "$_keylength"
  2425. ;;
  2426. createCSR)
  2427. createCSR "$_domain" "$_altdomains"
  2428. ;;
  2429. *)
  2430. _err "Invalid command: $_CMD"
  2431. showhelp;
  2432. return 1
  2433. ;;
  2434. esac
  2435. _ret="$?"
  2436. if [ "$_ret" != "0" ] ; then
  2437. return $_ret
  2438. fi
  2439. if [ "$_useragent" ] ; then
  2440. _saveaccountconf "USER_AGENT" "$_useragent"
  2441. fi
  2442. if [ "$_accountemail" ] ; then
  2443. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  2444. fi
  2445. }
  2446. if [ "$INSTALLONLINE" ] ; then
  2447. INSTALLONLINE=""
  2448. _installOnline $BRANCH
  2449. exit
  2450. fi
  2451. if [ -z "$1" ] ; then
  2452. showhelp
  2453. else
  2454. if echo "$1" | grep "^-" >/dev/null 2>&1 ; then
  2455. _process "$@"
  2456. else
  2457. "$@"
  2458. fi
  2459. fi